﻿//======================================================================
//
//        Copyright (C) 苏州逸仙软件    
//        All rights reserved
//
//        filename : AdminPublic.cs
//        description :
//
//        created by 周济 at 2010/12/13 8:41:46
//        mail:80406241@qq.com
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using huaguwang.swfupload;
using System.IO;
using System.Text;
using System.Net;
using System.Web.UI;

namespace huaguwang
{

    /// <summary>
    /// 后台统一处理类
    /// </summary>
    public static class AdminPublic
    {
        public static string Exp_PageSetText(this Page page, string url1, string url2, string title)
        {
            try
            {
                page.Exp_SaveURL(url1, page.Server.MapPath(url2));
                return "<a target=\"_blank\" href=\"" + url2 + "\"> " + title + "</a> 生成完毕<br/>";
            }
            catch(Exception ex)
            {
                var err = ex.Message.Replace("\n", "");
                return title + " 生成失败，错误原因：" + err + "<br/>";
            }

        }

        /// <summary>
        /// 获取历史页面ｕｒｌ，通过ｓｅｓｓｉｏｎ获得，如果没有则默认首页
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static string SessionURL_Get(this System.Web.UI.Page page)
        {
            var str = page.Session[ConstURL.Session_RURL].Exp_Trim();
            if(0 >= str.Length)
            {
                str = ConstURL.IndexName;
            }
            return str;
        }
        /// <summary>
        /// 设置历史页面ｕｒｌ，通过ｓｅｓｓｉｏｎ获得，如果没有则默认首页
        /// </summary>
        /// <param name="page"></param>
        /// <param name="strPath"></param>
        public static void SessionURL_Set(this System.Web.UI.Page page, string strPath)
        {
            var str = strPath.Exp_Trim();
            if(0 >= str.Length)
            {
                str = ConstURL.IndexName;
            }
            page.Session[ConstURL.Session_RURL] = strPath;
        }


        /// <summary>
        /// 统一url常数
        /// </summary>
        public static class ConstURL
        {
            /// <summary>
            /// 登录页面
            /// </summary>
            public const string LoginName = "/user/login.aspx";
            /// <summary>
            /// 注册页面
            /// </summary>
            public const string RegisterName = "/user/register.aspx";
            /// <summary>
            /// 网页首页
            /// </summary>
            public const string IndexName = "/";
            /// <summary>
            /// 前一个页面的ｕｒｌ资料存储
            /// </summary>
            public const string Session_RURL = "s_RULR";
        }
        ///<summary>
        /// 写资料到文件中
        /// </summary>
        /// <param name="FilePath">文件路径</param>
        /// <param name="sb">要写入的内容</param>
        public static void FileWrite(string FilePath, string sb)
        {
            string DirPath = FilePath.Substring(0, FilePath.LastIndexOf(@"\"));


            DirectoryInfo dir = new DirectoryInfo(DirPath);
            if(!dir.Exists)
            {
                dir.Create();
            }


            StreamWriter sw;
            if(File.Exists(FilePath))
            {
                //sw = new StreamWriter(FilePath, true, Encoding.UTF8);
                sw = new StreamWriter(FilePath, false, Encoding.UTF8);
            }
            else
            {
                sw = File.CreateText(FilePath);
            }
            sw.WriteLine(sb);
            sw.Close();
            sw.Dispose();
        }
        /// <summary>
        /// 保存url到文件
        /// </summary>
        /// <param name="url">相对网站根部地址,不带http,但是需要带有斜杠/</param>
        /// <param name="SavePath">保存到的地址</param>
        public static void Exp_SaveURL(this System.Web.UI.Page page, string url, string SavePath)
        {

            HttpWebRequest req;
            try
            {
                var strURL = page.Request.Url.Authority;
                url = "http://" + strURL + url;
                req = (HttpWebRequest)WebRequest.Create(url);
            }
            catch(Exception)
            {
                throw new Exception("url资料错误:" + url);
            }

            HttpWebResponse rep;
            try
            {
                rep = (HttpWebResponse)req.GetResponse();
            }
            catch(Exception ex)
            {
                throw ex;
            }

            string strResult = "";
            using(Stream streamReceive = rep.GetResponseStream())
            {
                using(StreamReader streamReader = new StreamReader(streamReceive))
                {

                    strResult = streamReader.ReadToEnd();
                }
            }
            if(strResult == null)
            {
                strResult = "";
            }
            if(strResult.Trim().Length <= 0)
            {
                throw new Exception("页面内容获取失败");
            }
            try
            {
                FileWrite(SavePath, strResult);
            }
            catch(Exception)
            {
                throw new Exception("资料写文件失败");
            }

        }


        public const string M_SessionUser = "M_SessionUser";
        public const string M_CookiesUserID = "M_CookiesUserID";
        public const string M_CookiesUserName = "M_CookiesUserName";
        public const string M_CookiesUserPW = "M_CookiesUserPW";
        /// <summary>
        /// 获得登录用户资料,如果没有则返回null,先获取session,然后获取cookie,
        /// 此方法不会自动跳转页面
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static M_T_Member_Exp.M_T_MemberLogin Exp_GetMember(this System.Web.UI.Page page)
        {
            //先看session中有没有用户
            var sess = page.Session[M_SessionUser];
            if(sess == null)
            {
                //如果没有则判断cookie中有咩有
                return page.Exp_GetMemberCookies();
            }
            else
            {
                try
                {
                    //如果有,就转换资料
                    var model = (M_T_Member_Exp.M_T_MemberLogin)sess;
                    return model;
                }
                catch
                {
                    return null;
                }


            }

        }
        /// <summary>
        /// 从cook中获取信息,如果有,则匹配数据库,并且写session
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static M_T_Member_Exp.M_T_MemberLogin Exp_GetMemberCookies(this System.Web.UI.Page page)
        {
            var sess = page.Response.Cookies[M_SessionUser];
            if(sess == null)
            {
                return null;
            }
            else
            {
                //cookie中只保存id,用户密码,和用户名,所以需要重新查询一次数据库
                var id = sess.Values[M_CookiesUserID].Exp_IntTryParse();
                var pass = sess.Values[M_CookiesUserPW].Exp_Trim();
                var dal = new D_T_Member_Exp();
                var model = dal.MemBerLogin(id, pass);
                //调用统一转换方法
                var modelRef = model.Exp_ToModelLogin();
                if(modelRef == null)
                {
                    return null;
                }
                else
                {
                    //查询成功,重新添加session
                    page.Session.Remove(M_SessionUser);
                    page.Session.Add(M_SessionUser, modelRef);
                    return modelRef;
                }
            }
        }
        /// <summary>
        /// 专门用来把单一的会员对象转换成登录对象
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static M_T_Member_Exp.M_T_MemberLogin Exp_ToModelLogin(this M_T_Member model)
        {
            if(model == null)
            {
                return null;
            }
            else
            {
                return new M_T_Member_Exp.M_T_MemberLogin(model);
            }
        }

        /// <summary>
        /// 统一错误判断
        /// </summary>
        /// <param name="hg"></param>
        public static void Try(Action hg)
        {
            Try<string>(() =>
            {
                hg();
                return string.Empty;
            });
        }
        public static T Try<T>(Func<T> hg)
        {
            try
            {
                return hg();
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// 获取工具条的skey,然后提示并跳转
        /// </summary>
        /// <param name="page"></param>
        /// <param name="wtb"></param>
        /// <param name="url"></param>
        public static void Exp_PageSkyAlterReplace(this System.Web.UI.Page page, string url, string sKey, string strMsg)
        {
            page.Exp_PageAlterReplace(strMsg, url + "?" + sKey);
        }
        /// <summary>
        /// 专门用来绑定通用类型下拉树的方法
        /// </summary>
        /// <param name="downList">要绑定的DownListTree对象</param>
        public static void Exp_BindClassTree(this HGDownListTree downList)
        {
            D_T_Category_Exp _d_class = new D_T_Category_Exp();
            List<M_T_Category> cList = new List<M_T_Category>();
            cList = _d_class.GetClassList();
            var TreeList = from li in cList
                           select new HGDownListTree.TreeListItem()
                           {
                               ID = li.id,
                               Depth = li.Depth,
                               ParentID = li.ParentId,
                               ShowTitle = li.CateName,
                               ShowDescription = li.DescriptionWord
                           };

            downList.BindData(TreeList.ToList());
        }

        /// <summary>
        /// 专门用来绑定新闻类型下拉树的方法
        /// </summary>
        /// <param name="downList">要绑定的DownListTree对象</param>
        public static void Exp_BindNewsClassTree(this HGDownListTree downList)
        {
            D_T_NewsCate_Exp _d_class = new D_T_NewsCate_Exp();
            List<M_T_NewsCate> cList = new List<M_T_NewsCate>();
            cList = _d_class.GetClassList();
            var TreeList = from li in cList
                           select new HGDownListTree.TreeListItem()
                           {
                               ID = li.id,
                               Depth = li.Depth,
                               ParentID = li.ParentId,
                               ShowTitle = li.CateName,
                               ShowDescription = li.DescriptionWord
                           };

            downList.BindData(TreeList.ToList());
        }
    }
}
